package es.udc.emarketapp.emarket.model.purchase.purchaseFacade.actions;

import es.udc.emarketapp.emarket.model.order.vo.OrderVO;
import es.udc.emarketapp.emarket.model.orderDetails.dao.SQLOrderDetailsDAO;
import es.udc.emarketapp.emarket.model.orderDetails.dao.SQLOrderDetailsDAOFactory;
import es.udc.emarketapp.emarket.model.orderDetails.vo.OrderDetailsVO;
import es.udc.emarketapp.emarket.model.orderLine.dao.SQLOrderLineDAO;
import es.udc.emarketapp.emarket.model.orderLine.dao.SQLOrderLineDAOFactory;
import es.udc.emarketapp.emarket.model.orderLine.vo.OrderLineVO;
import es.udc.emarketapp.emarket.model.purchase.purchaseFacade.vo.OrderChunkVO;


import java.sql.Connection;
import java.util.List;

import es.udc.fbellas.j2ee.util.exceptions.InternalErrorException;
import es.udc.fbellas.j2ee.util.sql.NonTransactionalPlainAction;
import java.util.ArrayList;

public class FindOrdersByPurchaseAction implements NonTransactionalPlainAction {

    private Long idPurchase;
    private int startIndex;
    private int count;

    public FindOrdersByPurchaseAction(Long idPurchase, int startIndex, int count) {

        this.idPurchase = idPurchase;
        this.startIndex = startIndex;
        this.count = count;
    }

    /**
     *
     * @return An instance of <code>OrderDetailsChunkVO</code> objects.
     */
    public Object execute(Connection connection) throws InternalErrorException {

        /*
         * Find count+1 purchases to determine if there exist more products
         * above the specified range.
         */
        SQLOrderDetailsDAO orderDetailsDAO = SQLOrderDetailsDAOFactory.getDAO();


        List<OrderDetailsVO> orderDetailsVOs = orderDetailsDAO.findByPurchase(connection,
                idPurchase, startIndex, count + 1);
        boolean existMoreOrders = orderDetailsVOs.size() == (count + 1);

        /*
         * Remove the last account from the returned list if there exist more
         * accounts above the specified range.
         */
        if (existMoreOrders) {
            orderDetailsVOs.remove(orderDetailsVOs.size() - 1);
        }

        /*Se recorre la lista de orderDetails y se crea la lista de orders 
         * a devolver, cada order con su orderDetails y su lineOrders
         *  
         */


        SQLOrderLineDAO orderLineDAO = SQLOrderLineDAOFactory.getDAO();

        List<OrderVO> orders = new ArrayList<OrderVO>();
        List<OrderLineVO> orderLines = null;


        for (OrderDetailsVO orderDetails : orderDetailsVOs) {

            orderLines = orderLineDAO.findByOrder(connection,
                    orderDetails.getnPedido(), orderDetails.getnCompra(), 
                    1, Integer.MAX_VALUE);

            orders.add(new OrderVO(orderDetails, orderLines));
        }

        return new OrderChunkVO(orders, existMoreOrders);

    }
}
